<?php

class Core_Utilities_Upload{

	public static $CHECK = false;
	function __construct(){

	}

	function doUpload($name, $folder='media'){

		if($_FILES[$name]['name']!=''){
            $arrayTmp = Zend_Registry::get('config_site');
			if (($_FILES[$name]["size"]/1024 <= $arrayTmp['photo_size'])*1024)
			{
				
				if ($_FILES[$name]["error"] > 0){
					return 3; //file có lỗi
				}else{

					$name_file = substr(strtolower($_FILES[$name]["name"]),0,strlen($_FILES[$name]["name"])-4);
					$ext = substr(strtolower($_FILES[$name]["name"]),-3);
					$convert_name = md5($name_file.time()).'.'.$ext;
					$path=$_FILES[$name]['tmp_name'];
					$thumb = $this->make_thumb($convert_name,$path,'photo','true','media/');
					//move_uploaded_file($_FILES[$name]["tmp_name"], $path);
					$arrDate = getdate();
					return $arrDate['year'].'/'.$arrDate['mon'].'/'.$convert_name;
				}				
			}else{
				# invalid file
				return 2;  // dung lượng  lớn hơn cho phép
			}
		}
		return '';
	}
   
    function getTypeFile($file){
        return $this->getExtension($_FILES[$file]['name']);
    }
    
	function make_thumb($img_name,$path,$type='photo',$datefolder='true',$fpath='')
	{

		if(self::$CHECK) {
			$arrBlogConfig = array(
				'thumb'=>array('width'=>122,'height'=>82),
				'full'=>array('width'=>600,'height'=>500)
			);
		} else {
			$arrayTmp = Zend_Registry::get('config_site');
			$arrBlogConfig = $arrayTmp[$type];
		}



		$ext=$this->getExtension($img_name);
		//creates the new image using the appropriate function from gd library

		foreach($arrBlogConfig as $key => $tmpBlog)
		{
			if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
			$src_img=imagecreatefromjpeg($path);

			if(!strcmp("png",$ext))
			$src_img=imagecreatefrompng($path);

			if(!strcmp("gif",$ext))
			$src_img=imagecreatefromgif($path);


			//gets the dimmensions of the image
			$old_x=imageSX($src_img);
			$old_y=imageSY($src_img);
			$new_w = $tmpBlog['width'];
			$new_h=$tmpBlog['height'];
			
			$ratio1=$old_x/$new_w;
			$ratio2=$old_y/$new_h;
			if($ratio1>$ratio2 && $ratio1 > 1) {
				if($new_w < $old_x) {
					$thumb_w=$new_w;
					$thumb_h=$old_y/$ratio1;
				} else {
					$thumb_w = $old_x;
					$thumb_h=$old_y/$ratio1;
				}
			} else {
				if($new_h < $old_y) {
					$thumb_w=$new_w;
					$thumb_h=$old_y/$ratio1;
				} else {
					$thumb_w = $old_x;
					$thumb_h = $old_y;
				}
			}

			// we create a new image with the new dimmensions
			$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

			$im = imagecreatetruecolor(55, 30);
			$white = imagecolorallocate($im, 255, 255, 255);
			if (!@imagefilledrectangle($dst_img, 0, 0, $thumb_w-1, $thumb_h-1, $white)) {	// Fill the image black
				echo "ERROR:Could not fill new image";
				exit(0);
			}

			// resize the big image to the new created one
			imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
			if($datefolder=='true')
			{
				$arrDate = getdate();
				$dirPathYear = UPLOAD.$fpath.$type.'/'.$key.'/'.$arrDate['year'];
				$dirPathMonth = $dirPathYear.'/'.$arrDate['mon'].'/';

				if(!is_dir($dirPathMonth)){
					mkdir($dirPathMonth,0777,true);
				}
				$filename=$dirPathMonth.$img_name;
			}
			else
			{
				$filename=UPLOAD.$fpath.$type.'/'.$key.'/'.$img_name;
			}

			//var_dump($ext);
			// output the created image to the file. Now we will have the thumbnail into the file named by $filename
			if(!strcmp("png",$ext))
			imagepng($dst_img,$filename);
			else if(!strcmp("jpg",$ext)||!strcmp("jpeg",$ext))
			imagejpeg($dst_img,$filename);
			else if(!strcmp("gif",$ext))
			imagegif($dst_img,$filename);

			//destroys source and destination images.
			imagedestroy($dst_img);
			imagedestroy($src_img);
		}
	}

	function showThumbnail() {
		$ext = $this->getExtension($_FILES["Filedata"]["name"]);
		//var_dump($_FILES["Filedata"]);		// Check the upload
		if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
			echo "ERROR:invalid upload";
			exit(0);
		}

		// Get the image and create a thumbnail
		if(!strcmp("png",$ext))
		$img = imagecreatefrompng($_FILES["Filedata"]["tmp_name"]);
		if(!strcmp("jpg",$ext))
		$img = imagecreatefromjpeg($_FILES["Filedata"]["tmp_name"]);
		if(!strcmp("gif",$ext))
		$img = imagecreatefromgif($_FILES["Filedata"]["tmp_name"]);

		if (!$img) {
			echo "ERROR:could not create image handle ". $_FILES["Filedata"]["tmp_name"];
			exit(0);
		}

		$width = imageSX($img);
		$height = imageSY($img);

		if (!$width || !$height) {
			echo "ERROR:Invalid width or height";
			exit(0);
		}

		// Build the thumbnail
		$target_width = 122;
		$target_height = 82;
		$target_ratio = $target_width / $target_height;

		$img_ratio = $width / $height;

		if ($target_ratio > $img_ratio) {
			$new_height = $target_height;
			$new_width = $img_ratio * $target_height;
		} else {
			$new_height = $target_width / $img_ratio;
			$new_width = $target_width;
		}

		if ($new_height > $target_height) {
			$new_height = $target_height;
		}
		if ($new_width > $target_width) {
			$new_height = $target_width;
		}

		$im = imagecreatetruecolor(122, 82);
		$white = imagecolorallocate($im, 255, 255, 255);
		$new_img = ImageCreateTrueColor(122, 82);
		if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, $white)) {	// Fill the image black
			echo "ERROR:Could not fill new image";
			exit(0);
		}

		if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) {
			echo "ERROR:Could not resize image";
			exit(0);
		}


		if (!isset($_SESSION["file_info"])) {
			$_SESSION["file_info"] = array();
		}
        

		// Use a output buffering to load the image into a variable
		ob_start();
		if(!strcmp("png",$ext))
		imagepng($new_img);
		if(!strcmp("jpg",$ext))
		imagejpeg($new_img);
		if(!strcmp("gif",$ext))
		imagegif($new_img);
		$imagevariable = ob_get_contents();
		ob_end_clean();

		$file_id = md5($_FILES["Filedata"]["tmp_name"] + rand()*100000);

		$_SESSION["file_info"]["$file_id"] = $imagevariable;
		$_SESSION["file_info"][] = $file_id;
        
		return $file_id;
	}

	function getExtension($str)
	{
		$i = strrpos($str,".");
		if (!$i) { return ""; }
		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);
		return $ext;
	}
}
#echo "Upload: " . $_FILES["image"]["name"] . "<br />";
#echo "Type: " . $_FILES["image"]["type"] . "<br />";
#echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
#echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";

?>